import React, { useEffect, useState } from 'react';
import {
    Form,
    Card,
    Input,
    Row,
    Col,
    Button,
    DatePicker,
    message,
    Upload,
    Tag,
    Modal,
    Radio,
    Select
} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import { history } from 'umi';
import { get as getPath } from 'object-path';
import BraftEditor from 'braft-editor';
// import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelpr from '@/utils/auth/helper';
import 'braft-editor/dist/index.css';
// import { FormContainer } from '@/components/UserForm';
import { uploadFile } from '@/utils/fileUpload';
import QueryPage from '@/components/QueryPage';
import { withRoutePage } from '@/utils/enhanceUtils';
import styles from './NewsManage.less';

const { checkCode } = authHelpr;
const { Option } = Select;

const getBase64 = file =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

const NewsEdit = ({
    props,
    newsManage,
    dispatch,
    form,
    loading,
    location,
    ...rags
}) => {
    const { authCode } = new AuthCode(rags.route.code);
    const { query } = location;
    // const [editorState, setEditorState] = useState(getPath(props, 'value'));
    // const [disabled, setDisabled] = useState('disabled');
    const disabled = 'disabled';
    const [visible, setVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState('button1');
    // const [editData, setEditData] = useState(false);
    const [newsCode, setNewsCode] = useState('');
    const [id, setId] = useState(null);
    const [hidden, setHidden] = useState(1);
    const { getFieldDecorator } = form;
    const { detailData, newsType } = newsManage;
    const formItemLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 }
    };

    // 获取“重新编辑”需要携带的参数
    const getEditData = () => {
        dispatch({
            type: 'newsManage/fetchEditNews',
            payload: {
                applicationNo: detailData.applicationNo
            },
            callback: res => {
                if (res.code === 10000) {
                    // setEditData(false);
                    history.push({
                        pathname: '/personal/portal/flow/mine/list/apply',
                        query: {
                            action: 'edit',
                            formDeploymentId: res.data.formDeploymentId,
                            templateId: res.data.templateId,
                            templateName: res.data.templateName,
                            applicationNo: res.data.applicationNo,
                            processDeploymentId: res.data.processDeploymentId,
                            id: res.data.applyId,
                            reedit: true
                        }
                    });
                } else {
                    // setEditData(false);
                    message.error(res.msg);
                }
            }
        });
    };
    // 获取详情
    const fetchDetail = () => {
        dispatch({
            type: 'newsManage/fetchNewsDetail',
            payload: {
                code: query.code,
                id: Number(query.id)
            }
        });
    };
    // 获取新闻类型列表
    const fetchNewsType = () => {
        dispatch({
            type: 'newsManage/fetchNewsType'
        });
    }
    // const handleEditorChange = state => {
    // setEditorState(state);
    // };
    const myUploadFn = param => {
        const params = {
            fileInfo: param
        };
        return uploadFile(params);
    };
    // 不允许添加尺寸大于100M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 100) {
            message.error('Size is greater than 1M!');
            return false;
        }
        return true;
    };
    // 卡片右侧两个按钮点击事件-弹窗
    const handleEdit = type => {
        setModalTitle(type);
        setVisible(true);
    };
    const handleOk = () => {
        if (modalTitle === 'button1') {
            form.validateFieldsAndScroll((err, fieldsValue) => {
                dispatch({
                    type: 'newsManage/fetchNewsHide',
                    payload: {
                        code: newsCode,
                        id,
                        hidden: fieldsValue.hidden
                    }
                });
            });
            fetchDetail();
        } else {
            // setEditData(true);
            getEditData();
        }
        setVisible(false);
    };

    const handleCancel = () => {
        setVisible(false);
    };
    useEffect(() => {
        fetchDetail();
        fetchNewsType();
        return () => {
            form.resetFields();
            dispatch({
                type: 'newsManage/clear'
            });
        };
    }, []);
    // const controls = [
    //     'undo',
    //     'redo',
    //     'separator',
    //     'font-size',
    //     'line-height',
    //     'letter-spacing',
    //     'separator',
    //     'text-color',
    //     'strike-through',
    //     'separator',
    //     'superscript',
    //     'subscript',
    //     'remove-styles',
    //     'separator',
    //     'text-indent',
    //     'text-align',
    //     'separator',
    //     'headings',
    //     'code',
    //     'separator',
    //     'media',
    //     'link',
    //     'hr',
    //     'separator',
    //     'clear'
    // ];

    // 图片预览功能
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState(null);
    // 预览图片
    const handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewVisible(true);
        setPreviewImage(file.url || file.preview);
    };
    const handlePreviewCancel = () => setPreviewVisible(false);

    return (
        <div>
            <QueryPage
                className={styles.searchwn}
                form={
                    <Card
                        bordered={false}
                        title={
                            <Row justify="space-between" type="flex">
                                <Col>官网新闻</Col>
                                <Col>
                                    <div
                                        style={{
                                            display: 'flex'
                                        }}
                                    >
                                        {checkCode(authCode('detail:set')) ? (
                                            <Button
                                                type="primary"
                                                style={{
                                                    position: 'relative',
                                                    verticalAlign: 'middle',
                                                    margin: '0 0 0 10px'
                                                }}
                                                disabled={
                                                    detailData.topping === 0
                                                }
                                                onClick={() => {
                                                    setNewsCode(
                                                        detailData.newsCode
                                                    );
                                                    setId(detailData.id);
                                                    setHidden(
                                                        detailData.hidden
                                                    );
                                                    handleEdit('button1');
                                                }}
                                            >
                                                新闻设置
                                            </Button>
                                        ) : null}

                                        {/* {checkCode(authCode('detail:reset')) ? (
                                            <Button
                                                type="primary"
                                                style={{
                                                    marginLeft: '10px'
                                                }}
                                                onClick={() =>
                                                    handleEdit('button2')
                                                }
                                                disabled={!query.isEdit}
                                                loading={editData}
                                            >
                                                重新编辑
                                            </Button>
                                        ) : null} */}
                                    </div>
                                </Col>
                            </Row>
                        }
                    >
                        <div style={{ fontSize: '16px', marginBottom: '32px' }}>
                            新闻内容
                            <span
                                style={{ fontSize: '14px', color: '#999999' }}
                            >
                                （两列输入框内容：左侧内容显示在中文官网，右侧内容显示在英文官网）
                            </span>
                        </div>
                        <Form {...formItemLayout}>
                            <Form.Item label="新闻名称：">
                                <div
                                    style={{
                                        width: 'calc(50% - 4px)',
                                        display: 'inline-block',
                                        position: 'relative',
                                        marginBottom: '20px'
                                    }}
                                >
                                    {getFieldDecorator('newsCnName', {
                                        initialValue: detailData.newsCnName
                                    })(
                                        <Input
                                            disabled={disabled}
                                            placeholder="请输入新闻名称-中文"
                                        />
                                    )}
                                    <p className={styles.tipsWn}>4-200</p>
                                </div>
                                <div
                                    style={{
                                        width: 'calc(50% - 4px)',
                                        marginLeft: '8px',
                                        display: 'inline-block',
                                        position: 'relative'
                                    }}
                                >
                                    {getFieldDecorator('newsEnName', {
                                        initialValue: detailData.newsEnName
                                    })(
                                        <Input
                                            placeholder="请输入新闻名称-英文"
                                            id="error"
                                            disabled={disabled}
                                        />
                                    )}
                                    <p className={styles.tipsWn}>4-200</p>
                                </div>
                            </Form.Item>

                            <Form.Item
                                style={{ marginBottom: '20px' }}
                                label="计划发布时间："
                                help="如在发布时间内还在审核中，会以最终通过的审批时间自动发布"
                            >
                                {getFieldDecorator('releaseTime', {
                                    initialValue: moment(detailData.releaseTime)
                                })(
                                    <DatePicker
                                        disabled={disabled}
                                        format="YYYY-MM-DD HH:mm"
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="创建时间：">
                                {getFieldDecorator('createTime', {})(
                                    <div>
                                        {moment(detailData.releaseTime).format(
                                            'YYYY-MM-DD HH:mm'
                                        )}
                                    </div>
                                )}
                            </Form.Item>
                            <Form.Item
                                style={{ marginBottom: '20px' }}
                                label="新闻类别："
                            >
                                {getFieldDecorator('newsTypes', {
                                    initialValue: detailData.newsTypes
                                })(
                                    <Select style={{ width: 120 }} disabled>
                                        {newsType && newsType.map(item => (
                                            <Option value={item.value}>{item.name}</Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item
                                style={{ marginBottom: '20px' }}
                                label="新闻列表图片："
                                help="尺寸170*170px，大小200KB以内，支持扩展名：.jpg
                            .png .gif"
                            >
                                {getFieldDecorator('officeFile', {
                                    initialValue: getPath(
                                        detailData.officeFile,
                                        '0.url',
                                        ''
                                    )
                                })(
                                    <Upload
                                        disabled={disabled}
                                        listType="picture-card"
                                        fileList={[
                                            {
                                                name: getPath(
                                                    detailData.officeFile,
                                                    '0.originName',
                                                    ''
                                                ),
                                                uid: 'officeFile',
                                                status: 'done',
                                                url: getPath(
                                                    detailData.officeFile,
                                                    '0.url',
                                                    ''
                                                )
                                            }
                                        ]}
                                        onPreview={handlePreview}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item
                                style={{ marginBottom: '20px' }}
                                label="推荐新闻图片："
                                help="尺寸280*140px，大小200KB以内，支持扩展名：.jpg
                            .png .gif"
                            >
                                {getFieldDecorator('officeResFile', {
                                    initialValue: getPath(
                                        detailData.officeResFile,
                                        '0.url',
                                        ''
                                    )
                                })(
                                    <Upload
                                        className={styles.uploadImgwn}
                                        disabled={disabled}
                                        listType="picture-card"
                                        fileList={[
                                            {
                                                name: getPath(
                                                    detailData.officeResFile,
                                                    '0.originName',
                                                    ''
                                                ),
                                                uid: 'officeResFile',
                                                status: 'done',
                                                url: getPath(
                                                    detailData.officeResFile,
                                                    '0.url',
                                                    ''
                                                )
                                            }
                                        ]}
                                        onPreview={handlePreview}
                                    />
                                )}
                            </Form.Item>
                            <Modal visible={previewVisible} footer={null} onCancel={handlePreviewCancel}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                            <Form.Item label="新闻内容（中文）：">
                                {detailData.newsCnContent &&
                                    getFieldDecorator('newsCnContent', {
                                        initialValue:
                                            BraftEditor.createEditorState(
                                                `${detailData.newsCnContent}`
                                            ) ||
                                            BraftEditor.createEditorState(null),
                                        rules: [
                                            {
                                                validator: (
                                                    _,
                                                    value,
                                                    callback
                                                ) => {
                                                    if (value.isEmpty()) {
                                                        callback(
                                                            '请输入新闻内容'
                                                        );
                                                    } else {
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })(
                                        <BraftEditor
                                            // onChange={handleEditorChange}
                                            media={{
                                                uploadFn: myUploadFn,
                                                validateFn: myValidateFn,
                                                accepts: {
                                                    image:
                                                        'image/png,image/jpeg,image/gif'
                                                }
                                            }}
                                            readOnly
                                            imageControls={[
                                                {
                                                    onClick: () => {} // 指定控件点击后的回调，参数为当前图片的block对象
                                                },
                                                'size',
                                                'remove'
                                            ]}
                                            controls={[]}
                                            excludeControls={['fullscreen']}
                                            style={{
                                                border: '1px solid #d9d9d9',
                                                borderTopWidth: '1.02px',
                                                borderRadius: '4px',
                                                marginTop: '4px'
                                            }}
                                        />
                                    )}
                            </Form.Item>
                            <Form.Item label="新闻内容（英文）：">
                                {detailData.newsEnContent &&
                                    getFieldDecorator('newsEnContent', {
                                        initialValue:
                                            BraftEditor.createEditorState(
                                                `${detailData.newsEnContent}`
                                            ) ||
                                            BraftEditor.createEditorState(null),
                                        rules: [
                                            {
                                                validator: (
                                                    _,
                                                    value,
                                                    callback
                                                ) => {
                                                    if (value.isEmpty()) {
                                                        callback(
                                                            '请输入新闻内容'
                                                        );
                                                    } else {
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })(
                                        <BraftEditor
                                            // onChange={handleEditorChange}
                                            media={{
                                                uploadFn: myUploadFn,
                                                validateFn: myValidateFn,
                                                accepts: {
                                                    image:
                                                        'image/png,image/jpeg,image/gif'
                                                }
                                            }}
                                            readOnly
                                            imageControls={[
                                                {
                                                    onClick: () => {} // 指定控件点击后的回调，参数为当前图片的block对象
                                                },
                                                'size',
                                                'remove'
                                            ]}
                                            controls={[]}
                                            excludeControls={['fullscreen']}
                                            style={{
                                                border: '1px solid #d9d9d9',
                                                borderTopWidth: '1.02px',
                                                borderRadius: '4px',
                                                marginTop: '4px'
                                            }}
                                        />
                                    )}
                            </Form.Item>
                            <Form.Item
                                label="新闻标签（中文）："
                                style={{ marginBottom: '16px' }}
                            >
                                {getFieldDecorator('labelCn', {
                                    initialValue: detailData.labelCn || []
                                })(
                                    <div>
                                        {detailData.labelCn &&
                                            detailData.labelCn.map(item => (
                                                <Tag key={item.key}>
                                                    {item.value}
                                                </Tag>
                                            ))}
                                    </div>
                                )}
                            </Form.Item>
                            <Form.Item label="新闻标签（英文）：">
                                {getFieldDecorator('labelEn', {
                                    initialValue: detailData.labelEn || []
                                })(
                                    <div>
                                        {detailData.labelEn &&
                                            detailData.labelEn.map(item => (
                                                <Tag key={item.key}>
                                                    {item.value}
                                                </Tag>
                                            ))}
                                    </div>
                                )}
                            </Form.Item>
                        </Form>
                    </Card>
                }
            />
            <Modal
                title={modalTitle === 'button1' ? '新闻设置' : '重新编辑'}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                {modalTitle === 'button1' ? (
                    <Form layout="inline">
                        <Form.Item label="是否隐藏新闻：">
                            <div>
                                {getFieldDecorator('hidden', {
                                    initialValue: hidden,
                                    rules: [
                                        {
                                            required: true
                                        }
                                    ]
                                })(
                                    <Radio.Group>
                                        <Radio value={0}>是</Radio>
                                        <Radio value={1}>否</Radio>
                                    </Radio.Group>
                                )}
                                <p className={styles.modalLabel}>
                                    （隐藏的新闻不在官网新闻列表中显示，也不可置顶操作）
                                </p>
                            </div>
                        </Form.Item>
                    </Form>
                ) : (
                    <p>
                        编辑修改新闻标题或内容都要重新发起官网新闻发布审批流程，是否要重新编辑？
                    </p>
                )}
            </Modal>
        </div>
    );
};
export default withRoutePage(
    connect(({ loading, newsManage }) => ({
        loading: loading.models.newsManage,
        newsManage
    }))(Form.create()(NewsEdit))
);
